package com.ruoyi.system.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.CommonUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.AppDynamicLikeMapper;
import com.ruoyi.system.service.*;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.AppDynamicCommentMapper;

/**
 * 评论Service业务层处理
 *
 * @author ruoyi
 * @date 2023-02-27
 */
@Service
public class AppDynamicCommentServiceImpl extends ServiceImpl<AppDynamicCommentMapper, AppDynamicComment> implements IAppDynamicCommentService {
    @Autowired
    private AppDynamicCommentMapper appDynamicCommentMapper;
    @Autowired
    private IAppUserService iAppUserService;
    @Autowired
    private IAppDynamicService dynamicService;
    @Autowired
    private IAppUserRelationService userRelationService;
    @Autowired
    private IAppDynamicLikeService iAppDynamicLikeService;
    @Autowired
    private IAppDynamicCommentService iAppDynamicCommentService;
    @Autowired
    private IAppDynamicMsgService iAppDynamicMsgService;

    /**
     * 查询评论
     *
     * @param id 评论主键
     * @return 评论
     */
    @Override
    public AppDynamicComment selectAppDynamicCommentById(Long id) {
        return appDynamicCommentMapper.selectAppDynamicCommentById(id);
    }

    /**
     * 查询评论列表
     *
     * @param appDynamicComment 评论
     * @return 评论
     */
    @Override
    public List<AppDynamicComment> selectAppDynamicCommentList(AppDynamicComment appDynamicComment) {
        return appDynamicCommentMapper.selectAppDynamicCommentList(appDynamicComment);
    }

    /**
     * 新增评论
     *
     * @param appDynamicComment 评论
     * @return 结果
     */
    @Override
    public int insertAppDynamicComment(AppDynamicComment appDynamicComment) {
        return appDynamicCommentMapper.insertAppDynamicComment(appDynamicComment);
    }

    /**
     * 修改评论
     *
     * @param appDynamicComment 评论
     * @return 结果
     */
    @Override
    public int updateAppDynamicComment(AppDynamicComment appDynamicComment) {
        return appDynamicCommentMapper.updateAppDynamicComment(appDynamicComment);
    }

    /**
     * 批量删除评论
     *
     * @param ids 需要删除的评论主键
     * @return 结果
     */
    @Override
    public int deleteAppDynamicCommentByIds(Long[] ids) {
        return appDynamicCommentMapper.deleteAppDynamicCommentByIds(ids);
    }

    /**
     * 删除评论信息
     *
     * @param id 评论主键
     * @return 结果
     */
    @Override
    public int deleteAppDynamicCommentById(Long id) {
        return appDynamicCommentMapper.deleteAppDynamicCommentById(id);
    }

    @Override
    public List<AppDynamicComment> selectAppDynamicCommentList2(AppDynamicComment appDynamicComment) {
        return appDynamicCommentMapper.selectAppDynamicCommentList2(appDynamicComment);
    }

    @Override
    public AjaxResult commentDynamic(Long userId, Long dynamicId, String content) {
        AppUser userEntity = iAppUserService.selectAppUserByUserId(userId);
        // 保存评论
        AppDynamicComment commentEntity = new AppDynamicComment();
        commentEntity.setCrtTime(new Date());
        commentEntity.setDynamicId(dynamicId);
        commentEntity.setUserId(userId);
        commentEntity.setUserName(userEntity.getUsername());
        commentEntity.setUserHeadImg(userEntity.getHeadImg());
        commentEntity.setContent(CommonUtils.encodeNickname(content));
        appDynamicCommentMapper.insertAppDynamicComment(commentEntity);

        // 动态评论数增加
        dynamicService.addCommentCount(dynamicId);

        AppDynamic dynamicEntity = dynamicService.selectAppDynamicById(dynamicId);
        /*
         * 发送点赞通知消息
         * 对象：发送动态本人，点赞、评论的好友
         */
        List<AppDynamicMsg> msgList = Lists.newArrayList();
        String dynamicImg = "";
        // filterList内用户不再通知
        List<Long> filterList = Lists.newArrayList();
        filterList.add(userId);
        // 动态本人
        AppDynamicMsg msgEntity = new AppDynamicMsg();
        msgEntity.setCrtTime(commentEntity.getCrtTime());
        msgEntity.setUserId(dynamicEntity.getUserId());
        msgEntity.setDynamicId(dynamicId);
        msgEntity.setDynamicType(dynamicEntity.getType());
        msgEntity.setDynamicContent(dynamicEntity.getContent());
        if (dynamicEntity.getType() == 1) dynamicImg = JSONArray.parseArray(dynamicEntity.getImgs()).getString(0);
        else if (dynamicEntity.getType() == 2) dynamicImg = dynamicEntity.getVideoCover();
        msgEntity.setDynamicImg(dynamicImg);
        msgEntity.setMsgType(1);
        msgEntity.setFromUserId(userId);
        msgEntity.setFromUserName(userEntity.getUsername());
        msgEntity.setFromUserHeadImg(userEntity.getHeadImg());
        msgEntity.setCommentId(commentEntity.getId());
        msgEntity.setContent(CommonUtils.encodeNickname(content));
        if (!filterList.contains(msgEntity.getUserId())) { // 动态本人点赞不通知
            filterList.add(msgEntity.getUserId());
            msgList.add(msgEntity);
        }

        /*
         * 获取好友idList
         */
        AppUserRelation appUserRelation = new AppUserRelation();
        appUserRelation.setUserId(userId);
        appUserRelation.setSelfState(0);
        appUserRelation.setSelfIsBeLooked(0);
        appUserRelation.setOtherState(0);
        appUserRelation.setOtherIsLook(0);
        // 动态的可见权限
        // 用户与好友设置的朋友圈权限
        List<Long> friendIdList = userRelationService.selectAppUserIds(appUserRelation);
        /*
         * 获取点赞列表，通知点赞好友
         */
        AppDynamicLike dynamicLike = new AppDynamicLike();
        dynamicLike.setDynamicId(dynamicEntity.getId());
        if (friendIdList.size() > 0) {
            dynamicLike.setUserIds(friendIdList);
        }

        List<AppDynamicLike> likeList = iAppDynamicLikeService.selectAppDynamicLikeList(dynamicLike);


        for (AppDynamicLike dynamicLikeEntity : likeList) {
            msgEntity = new AppDynamicMsg();
            msgEntity.setCrtTime(commentEntity.getCrtTime());
            msgEntity.setUserId(dynamicLikeEntity.getUserId());
            msgEntity.setDynamicId(dynamicId);
            msgEntity.setDynamicType(dynamicEntity.getType());
            msgEntity.setDynamicContent(dynamicEntity.getContent());
            msgEntity.setDynamicImg(dynamicImg);
            msgEntity.setMsgType(1);
            msgEntity.setFromUserId(userId);
            msgEntity.setFromUserName(userEntity.getUsername());
            msgEntity.setFromUserHeadImg(userEntity.getHeadImg());
            msgEntity.setCommentId(commentEntity.getId());
            msgEntity.setContent(CommonUtils.encodeNickname(content));
            if (!filterList.contains(msgEntity.getUserId())) { // 已通知过得不通知
                filterList.add(msgEntity.getUserId());
                msgList.add(msgEntity);
            }
        }

        /*
         * 获取评论列表，通知评论好友
         */
        AppDynamicComment appDynamicComment = new AppDynamicComment();
        appDynamicComment.setDynamicId(dynamicEntity.getId());
        if (friendIdList.size() > 0) {
            appDynamicComment.setUserIds(friendIdList);
        }

        List<AppDynamicComment> commentList = iAppDynamicCommentService.selectAppDynamicCommentList2(appDynamicComment);

        for (AppDynamicComment dynamicCommentEntity : commentList) {
            msgEntity = new AppDynamicMsg();
            msgEntity.setCrtTime(commentEntity.getCrtTime());
            msgEntity.setUserId(dynamicCommentEntity.getUserId());
            msgEntity.setDynamicId(dynamicId);
            msgEntity.setDynamicType(dynamicEntity.getType());
            msgEntity.setDynamicContent(dynamicEntity.getContent());
            msgEntity.setDynamicImg(dynamicImg);
            msgEntity.setMsgType(1);
            msgEntity.setFromUserId(userId);
            msgEntity.setFromUserName(userEntity.getUsername());
            msgEntity.setFromUserHeadImg(userEntity.getHeadImg());
            msgEntity.setCommentId(commentEntity.getId());
            msgEntity.setContent(CommonUtils.encodeNickname(content));
            if (!filterList.contains(msgEntity.getUserId())) { // 已通知过得不通知
                filterList.add(msgEntity.getUserId());
                iAppDynamicMsgService.insertAppDynamicMsg(msgEntity);
            }
        }
        Map<String, Object> res = new HashMap<>();
        res.put("commentEntity", commentEntity);
        return AjaxResult.ok(0, "", res);
    }

    @Override
    public AjaxResult replyComment(Long userId, Long commentId, String content) {
        AppUser userEntity = iAppUserService.getById(userId);

        AppDynamicComment beCommentedEntity = iAppDynamicCommentService.selectAppDynamicCommentById(commentId);
        if (beCommentedEntity == null) {
            return AjaxResult.ok(-1, "参数错误", null);
        }
        // 保存回复评论
        AppDynamicComment replyEntity = new AppDynamicComment();
        replyEntity.setCrtTime(new Date());
        replyEntity.setDynamicId(beCommentedEntity.getDynamicId());
        replyEntity.setUserId(userId);
        replyEntity.setUserName(userEntity.getUsername());
        replyEntity.setUserHeadImg(userEntity.getHeadImg());
        replyEntity.setContent(CommonUtils.encodeNickname(content));
        replyEntity.setpId(commentId);
        replyEntity.setReplyUserId(beCommentedEntity.getUserId());
        replyEntity.setReplyUserName(beCommentedEntity.getUserName());
        iAppDynamicCommentService.insertAppDynamicComment(replyEntity);

        // 动态评论数增加
        dynamicService.addCommentCount(beCommentedEntity.getDynamicId());

        AppDynamic dynamicEntity = dynamicService.selectAppDynamicById(beCommentedEntity.getDynamicId());
        String dynamicImg = "";
        // 通知被回复人
        AppDynamicMsg msgEntity = new AppDynamicMsg();
        msgEntity.setCrtTime(replyEntity.getCrtTime());
        msgEntity.setUserId(beCommentedEntity.getUserId());
        msgEntity.setDynamicId(beCommentedEntity.getDynamicId());
        msgEntity.setDynamicType(dynamicEntity.getType());
        msgEntity.setDynamicContent(dynamicEntity.getContent());
        if (dynamicEntity.getType() == 1) dynamicImg = JSONArray.parseArray(dynamicEntity.getImgs()).getString(0);
        else if (dynamicEntity.getType() == 2) dynamicImg = dynamicEntity.getVideoCover();
        msgEntity.setDynamicImg(dynamicImg);
        msgEntity.setMsgType(2);
        msgEntity.setFromUserId(userId);
        msgEntity.setFromUserName(replyEntity.getUserName());
        msgEntity.setFromUserHeadImg(replyEntity.getUserHeadImg());
        msgEntity.setCommentId(replyEntity.getId());
        msgEntity.setContent(CommonUtils.encodeNickname(content));
        msgEntity.setReplyUserName(beCommentedEntity.getUserName());
        iAppDynamicMsgService.insertAppDynamicMsg(msgEntity);

        Map<String, Object> map = new HashMap<>();
        map.put("commentEntity", replyEntity);
        return AjaxResult.ok(0, "", map);
    }

    @Override
    public int countByCommentIdAndUserId(Long commentId, Long userId) {
        AppDynamicComment comment = new AppDynamicComment();
        comment.setId(commentId);
        comment.setUserId(userId);
        List<AppDynamicComment> list = iAppDynamicCommentService.selectAppDynamicCommentList(comment);
        return list.size();
    }

    @Override
    public AjaxResult removeComment(Long commentId) {
        AppDynamicComment comment = iAppDynamicCommentService.selectAppDynamicCommentById(commentId);
        List<Long> commentIdList = Lists.newArrayList();
        commentIdList.add(commentId);

        recursiveChildComment(commentIdList, commentId);
        // 删除评论及子评论
        for (Long id : commentIdList) {
            iAppDynamicCommentService.deleteAppDynamicCommentById(id);
        }

        // 删除动态评论数
        dynamicService.reduceCommentCount(comment.getDynamicId(), commentIdList.size());

        // 删除通知
        for (Long id : commentIdList) {
            iAppDynamicMsgService.deleteAppDynamicMsgById(id);
        }

        return AjaxResult.ok(0, "删除评论成功", null);
    }

    /**
     * 递归获取评价及所有子评价
     *
     * @param commentIdList
     * @param parentId
     */
    public void recursiveChildComment(List<Long> commentIdList, Long parentId) {
        AppDynamicComment comment = new AppDynamicComment();
        comment.setpId(parentId);
        List<AppDynamicComment> childList = iAppDynamicCommentService.selectAppDynamicCommentList(comment);

        for (AppDynamicComment dynamicCommentment : childList) {
            commentIdList.add(dynamicCommentment.getId());
            recursiveChildComment(commentIdList, dynamicCommentment.getId());
        }
    }

}
